package com.study.store;

import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.study.store.s3.S3Help;

import java.io.InputStream;

/**
 * @author tc
 * @date 2019/1/2
 */
public class FileStoreServiceImpl implements FileStoreService {

    @Override
    public FileStoreResult upload(Invocation invocation) {
        FileStoreResult result = new FileStoreResult();
        PutObjectResult putObjectResult;

        if (invocation.getObject().isEncrypt()) {
            putObjectResult = S3Help.putObject(invocation.getClient(),
                invocation.getMetadata().getActiveBucketName(), invocation.getObject().getKey(),
                invocation.getObject().getEncryptInputStream());
        } else {
            if (invocation.getObject().getFile() == null) {
                putObjectResult = S3Help.putObject(invocation.getClient(),
                    invocation.getMetadata().getActiveBucketName(), invocation.getObject().getKey(),
                    invocation.getObject().getInputStream());
            } else {
                putObjectResult = S3Help.putObject(invocation.getClient(),
                    invocation.getMetadata().getActiveBucketName(), invocation.getObject().getKey(),
                    invocation.getObject().getFile());
            }
        }

        result.seteTag(putObjectResult.getETag());
        result.setResult(true);
        result.setMetadata(putObjectResult.getMetadata());

        return result;
    }

    @Override
    public FileStoreResult download(Invocation invocation) {
        FileStoreResult result = new FileStoreResult();

        S3Object object = S3Help.getObject(invocation.getClient(), invocation.getMetadata().getActiveBucketName(),
            invocation.getObject().getKey());

        S3ObjectInputStream storeSteam = object.getObjectContent();
        InputStream resultIs = null;

        if (invocation.getObject().isEncrypt()) {
            // 解密
            //resultIs =
        } else {
            resultIs = storeSteam;
        }

        FileObject fileObject = new FileObject();
        // file other message

        result.setObject(fileObject);
        result.setInputStream(resultIs);
        result.setResult(true);
        result.setMetadata(object.getObjectMetadata());

        return result;
    }

    @Override
    public FileStoreResult url(Invocation invocation) {
        FileStoreResult result = new FileStoreResult();

        String url = S3Help.getUrl(invocation.getClient(), invocation.getMetadata().getActiveBucketName(),
            invocation.getObject().getKey());

        result.setUrl(url);
        result.setResult(true);

        return result;
    }

    @Override
    public FileStoreResult transfer(Invocation invocation) {
        return null;
    }

    @Override
    public FileStoreResult delete(Invocation invocation) {
        return null;
    }

}
